package com.da.javatest.webflux;

import java.io.IOException;

import com.da.javatest.webflux.handler.UserHandler;
import com.da.javatest.webflux.service.UserService;
import com.da.javatest.webflux.service.impl.UserServiceImpl;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;

/**
 * @author JokerDa.
 * @date 2021/1/6 16:34
 * Description:
 */
public class Server {
    // 创建router路由
    public RouterFunction<ServerResponse> routingFunction() {
        UserService userService = new UserServiceImpl();
        UserHandler userHandler = new UserHandler(userService);
        // 设置路由,带{id}的需要放在最后面，不然会有bug
        return RouterFunctions
            .route(POST("/user2/save").and(accept(MediaType.APPLICATION_JSON)), userHandler::saveUser)
            .andRoute(GET("/user2/all").and(accept(MediaType.APPLICATION_JSON)), userHandler::getAllUser)
            .andRoute(GET("/user2/{id}").and(accept(MediaType.APPLICATION_JSON)), userHandler::getUserById);
    }

    // 创建服务器完成适配
    public void createReactorServer() {
        // 路由和handler的适配
        RouterFunction<ServerResponse> route = routingFunction();
        HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        // 创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(adapter).bindNow();
    }

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("enter to exit");
        System.in.read();
    }
}
